package com.efei.jdbc.dao;

import com.efei.jdbc.config.QueryDaoFactoryBean;
import com.efei.jdbc.sql.SqlSelect;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.relational.core.sql.SQL;
import org.springframework.data.relational.core.sql.Select;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import java.beans.Introspector;
import java.util.List;

public abstract class AbstractQueryDao implements QueryDao, InitializingBean, BeanFactoryAware {

    protected NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    protected QueryDao queryDao;

    protected BeanFactory beanFactory;

    @Override
    public Page<?> selectPageDataBySQL(SqlSelect sql, Pageable pageable) {
        return queryDao.selectPageDataBySQL(sql,pageable);
    }

    @Override
    public List<?> selectDataBySQL(SqlSelect sql) {
        return queryDao.selectDataBySQL(sql);
    }

    @Override
    public <T> T selectOne(SqlSelect sql, Class<T> clz) {
        return queryDao.selectOne(sql,clz);
    }

    @Override
    public <T> T selectOne(SqlSelect sql) {
        return queryDao.selectOne(sql);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        QueryDaoFactoryBean bean = beanFactory.getBean(QueryDaoFactoryBean.class);
        String beanName = Introspector.decapitalize(bean.getClass().getSimpleName());
        queryDao = (QueryDao)beanFactory.getBean(beanName);
        namedParameterJdbcTemplate = beanFactory.getBean(NamedParameterJdbcTemplate.class);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}
